package bll

import (
	"context"
	"fmt"
	"ota/store/redis"
)

const (
	OnlineRedisKey = "signal:online"
)

// IsOnline check device is online
func IsOnline(sn string) bool {
	return redis.KV.HExists(context.Background(), OnlineRedisKey, sn).Val()
}

func RpcCall(sn string, callback func(addr string, err error) error) error {
	res, err := redis.KV.HMGet(context.Background(), OnlineRedisKey, sn).Result()
	if err != nil {
		return err
	}
	if len(res) == 0 {
		return fmt.Errorf("emtpy result from redis key:%v %v", OnlineRedisKey, sn)
	}
	var addr string
	if v, ok := res[0].(string); ok {
		addr = v
	}
	if addr == "" {
		return callback(addr, fmt.Errorf("address is empty"))
	}
	return callback(addr, nil)
}
